﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
}
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>生产工单基本信息显示页面</title>
    <!-- 引用本地 layui.css -->
    <link href="~/lib/layuiadmin/layui/css/layui.mobile.css" rel="stylesheet" />
    <link href="~/lib/layuiadmin/layui/css/layui.css" rel="stylesheet" />
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="~/lib/jquery/dist/jquery.js"></script>
    @* <script src="https://cdn.jsdelivr.net/npm/layui@2.8.11/dist/layui.min.js"></script> *@
    @*<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/layui@2.8.11/dist/css/layui.min.css"> *@
    <style>
        /* 新增导航栏样式 */
        .custom-navbar {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            background: #fff;
            z-index: 999;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }

        .nav-tabs {
            padding: 0 20px;
            border-bottom: 1px solid #e6e6e6;
        }

            .nav-tabs .layui-this {
                border-bottom-color: #5FB878 !important;
            }

        .page-content {
            margin-top: 60px; /* 给导航栏留出空间 */
            padding: 20px;
        }
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            margin: 0;
            background-color: #f4f4f4; /* 可根据需要调整背景颜色 */
        }

        .layui-form {
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            width: 80%; /* 可根据需要调整表单宽度 */
            max-width: 1200px; /* 可根据需要调整表单最大宽度 */
        }

        /* 避免表单标签换行 */
        .layui-form-label {
            white-space: nowrap;
            overflow: visible;
            text-overflow: clip;
        }

        /* 为输入框和选择框设置最小宽度 */
        .layui-input-inline {
            min-width: 200px; /* 可根据实际情况调整 */
        }

        /* 避免表格单元格内容换行 */
        .layui-table td {
            white-space: nowrap;
            overflow: visible;
            text-overflow: clip;
        }


            /*工艺流程相关样式*/

            /* 固定列样式 */
            .layui-table th.sticky-col,
            .layui-table td.sticky-col {
                position: sticky;
                background-color: #fff;
                z-index: 1;
            }

            /* 左侧固定列 */
            .layui-table th:first-child,
            .layui-table td:first-child {
                left: 0;
                box-shadow: 2px 0 4px rgba(0,0,0,0.1);
            }

            /* 右侧固定列 */
            .layui-table th:last-child,
            .layui-table td:last-child {
                right: 0;
                box-shadow: -2px 0 4px rgba(0,0,0,0.1);
            }
    </style>
</head>

<body>

    <div class="custom-navbar">
        <ul class="layui-nav nav-tabs" lay-filter="navFilter">
            <li class="layui-nav-item layui-this"><a href="javascript:;" data-page="basicInfo">工单信息</a></li>
            <li class="layui-nav-item"><a href="javascript:;" data-page="reportRecords">报工记录</a></li>
            <li class="layui-nav-item"><a href="javascript:;" data-page="operationLog">操作记录</a></li>
            <li class="layui-nav-item" style="float: right;">
                <a href="javascript:;">
                    <i class="layui-icon layui-icon-more-vertical"></i>
                </a>
                <dl class="layui-nav-child">
                    <dd><a href="javascript:;" id="btnOnline">上线</a></dd>
                    <dd><a href="javascript:;" id="btnClose">关闭</a></dd>
                    <dd><a href="javascript:;" id="btnPrint">打印</a></dd>
                </dl>
            </li>
            <li class="layui-nav-item" style="float: right;">
                <div class="stamp" style="color:#5FB878;font-weight: bold;">已下达</div>
            </li>
        </ul>
    </div>


    <!-- 工单信息 -->
    <div class="page-content" id="basicInfo">
        <form class="layui-form">
            <a href="http://localhost:5223/workorder/scworkorderquery" class="back-button">返回主页面</a>
            <!-- 基础信息部分 -->
            <div class="layui-form-item">
                <label class="layui-form-label">基础信息</label>
            </div>
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">工单名称</label>
                        <div class="layui-input-inline">
                            <input type="text" name="workOrderName" id="workOrderName" lay-verify="required"
                                   autocomplete="off" class="layui-input">
                            <span class="layui-form-mid layui-word-aux">
                                <input type="checkbox" name="systemNumber" lay-filter="systemNumber"
                                       title="系统编号" checked lay-skin="primary">
                            </span>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">* 关联生产单号</label>
                        <div class="layui-input-inline">
                            <select name="associatedProductionOrderNumber" id="associatedProductionOrderNumber" lay-verify="required" lay-search>
                                <option value="">请选择生产单号</option>
                            </select>
                            <i class="layui-icon layui-icon-clipboard"></i>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">关联项目</label>
                        <div class="layui-input-inline">
                            <select name="associatedProject" id="associatedProject" lay-verify="required" lay-search>
                                <option value="">请选择项目名称</option>
                                <option value="项目A">项目A</option>
                                <option value="项目B">项目B</option>
                                <option value="项目C">项目C</option>
                                <option value="项目D">项目D</option>
                                <option value="项目E">项目E</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">负责人</label>
                        <div class="layui-input-inline">
                            <input type="text" name="personinCharge" id="personinCharge" placeholder="请选择负责人" autocomplete="off"
                                   class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">备注</label>
                        <div class="layui-input-block">
                            <textarea name="remarks" id="remarks" placeholder="请输入备注" class="layui-textarea"></textarea>
                        </div>
                    </div>
                </div>
                <div class="layui-col-md6">

                    <div class="layui-form-item">
                        <label class="layui-form-label">销售订单</label>
                        <div class="layui-input-inline">
                            <input type="text" name="salesOrder" placeholder="请选择销售单号" autocomplete="off"
                                   class="layui-input" id="salesOrder" lay-reqtext="请填写销售订单号">
                            <i class="layui-icon layui-icon-clipboard"></i>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">工单日期</label>
                        <div class="layui-input-inline" style="position: relative;">
                            <!-- 新增定位上下文 -->
                            <input type="text"
                                   name="workOrderDate"
                                   placeholder="请选择日期"
                                   autocomplete="off"
                                   class="layui-input"
                                   id="workOrderDate"
                                   style="padding-right: 28px;"> <!-- 增加右侧内边距 -->
                            <i class="layui-icon layui-icon-date"
                               style="position: absolute; right: 5px; top: 50%; transform: translateY(-50%); pointer-events: none;"></i>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">所属部门</label>
                        <div class="layui-input-inline">
                            <select name="affiliatedDepartment" id="affiliatedDepartment" lay-verify="required" lay-search>
                                <option value="">请选择部门</option>
                                <option value="设计部">设计部</option>
                                <option value="采购部">采购部</option>
                                <option value="计划部">计划部</option>
                                <option value="设备部">设备部</option>
                                <option value="质量部">质量部</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 生产物品部分 -->
            <div class="layui-form-item">
                <label class="layui-form-label">生产物品</label>
            </div>
            <div class="layui-row layui-col-space15" id="wupinLiST">
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">* 物品名称</label>
                        <div class="layui-input-inline">
                            <input type="text" name="itemName" id="itemName" placeholder="请输入" autocomplete="off"
                                   class="layui-input" readonly>
                            @*  <i class="layui-icon layui-icon-box"></i> *@
                            <button type="button" class="layui-btn layui-btn-xs selectMaterialButton">选择物品</button>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">规格型号</label>
                        <div class="layui-input-inline">
                            <input type="text" name="specification" id="specification" placeholder="请输入" autocomplete="off"
                                   class="layui-input" readonly>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">物品类别</label>
                        <div class="layui-input-inline">
                            <input type="text" name="itemCategory" id="itemCategory" placeholder="请输入" autocomplete="off"
                                   class="layui-input" readonly>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">计划开始时间</label>
                        <div class="layui-input-inline" style="position: relative;">
                            <!-- 新增定位上下文 -->
                            <input type="date"
                                   name="plannedStartTime"
                                   placeholder="请选择日期"
                                   autocomplete="off"
                                   class="layui-input"
                                   id="plannedStartTime"
                                   style="padding-right: 28px;"> <!-- 增加右侧内边距 -->
                            <i class="layui-icon layui-icon-date"
                               style="position: absolute; right: 5px; top: 50%; transform: translateY(-50%); pointer-events: none;"></i>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">计划产量</label>
                        <div class="layui-input-inline">
                            <input type="number" name="plannedOutput" id="plannedOutput" placeholder="请输入计划生成量" autocomplete="off"
                                   class="layui-input">
                        </div>
                    </div>
                </div>
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">物品编号</label>
                        <div class="layui-input-inline">
                            <input type="text" name="itemNumber" id="itemNumber" placeholder="请输入" autocomplete="off"
                                   class="layui-input" readonly>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">单位</label>
                        <div class="layui-input-inline">
                            <input type="text" name="unit" id="unit" placeholder="请输入" autocomplete="off" class="layui-input" readonly>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">物品分类</label>
                        <div class="layui-input-inline">
                            <input type="text" name="itemClassification" id="itemClassification" placeholder="请输入" autocomplete="off"
                                   class="layui-input" readonly>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">计划结束时间</label>
                        <div class="layui-input-inline" style="position: relative;">
                            <!-- 新增定位上下文 -->
                            <input type="date"
                                   name="plannedEndTime"
                                   placeholder="请选择日期"
                                   autocomplete="off"
                                   class="layui-input"
                                   id="plannedEndTime"
                                   style="padding-right: 28px;"> <!-- 增加右侧内边距 -->
                            <i class="layui-icon layui-icon-date"
                               style="position: absolute; right: 5px; top: 50%; transform: translateY(-50%); pointer-events: none;"></i>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 工艺流程部分 -->
            <div class="layui-form-item">
                <label class="layui-form-label">工艺流程</label>
            </div>
            <div id="processFlowTable" style="width: 100%; overflow-x: auto;">
                <table class="layui-table" style="min-width: 1600px;">
                    <thead>
                        <tr>
                            <th style="position: sticky; left: 0; background: #fff; z-index: 1;">序号</th>
                            <th>工序编码</th>
                            <th>工序名称</th>
                            <th>加工顺序</th>
                            <th>工艺流程</th>
                            <th>负责人</th>
                            <th>所在部门</th>
                            <th>计划开始时间</th>
                            <th>计划结束时间</th>
                            <th>计划产量</th>
                            <th>备注</th>
                            <th style="position: sticky; right: 0; background: #fff; z-index: 1;">操作</th>
                        </tr>
                    </thead>
                    <tbody id="processFlowBody">
                        <!-- 初始行数据可根据需要添加 -->
                    </tbody>
                </table>
                <button type="button" class="layui-btn" id="addProcessFlowRow" style="margin: 10px 0;">添加</button>
            </div>

            <!-- 附件部分 -->
            <div class="layui-form-item">
                <label class="layui-form-label">附件</label>
                <div class="layui-input-block">
                    <button type="button" class="layui-btn" id="uploadButton">选择图片上传</button>
                    <input type="file" name="wenJian" id="wenJian" multiple accept="image/*" class="layui-upload-file"
                           style="display: none;">
                    <!-- 图片预览区域 -->
                    <div id="imagePreview" style="margin-top: 10px; display: flex; flex-wrap: wrap;"></div>
                </div>
            </div>

            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button type="submit" class="layui-btn" lay-submit lay-filter="submitForm">提交</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </div>



    <!-- 报工记录 -->
    <div class="page-content" id="reportRecords" style="display:none;">
        <div class="layui-card">
            <div class="layui-card-header">报工记录</div>
            <div class="layui-card-body">
                <!-- 此处添加报工记录表格 -->
                <table class="layui-table" id="ID-table-demo-filter" lay-filter="demoFilter"></table>

              

            </div>
        </div>
    </div>



    <!-- 操作记录 -->
    <div class="page-content" id="operationLog" style="display:none;">
        <div class="layui-card">
            <div class="layui-card-header">操作记录</div>
            <div class="layui-card-body">
               @*  <!--条件查询-->
                <form class="layui-form layui-row layui-col-space16" id="searchForm" lay-filter="searchFormFilter">
                    <div class="layui-col-sm3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">操作人</label>
                            <div class="layui-input-block">
                                <input type="text" name="CaoName" placeholder="操作人" class="layui-input">
                            </div>
                        </div>
                    </div>

                    <div class="layui-btn-container layui-col-xs12">
                        <button class="layui-btn" lay-submit lay-filter="searchSubmit">查询</button>
                        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                    </div>
                </form> *@
                <!-- 此处添加操作记录表格 -->
                <table class="layui-table" id="ID-table-demo-filters" ></table>


            </div>
        </div>
    </div>


    <!--重点修正2：修正工具列模板的class命名-->
    <script type="text/html" id="toolDemo">
               <div class="layui-clear-space">
          {{# if(d.zjStatus === false) { }} <!-- 仅当状态为false时显示按钮 -->
            <a class="layui-btn layui-btn-xs" lay-event="qualityCheck">质检</a>
          {{# } }}
        </div>
    </script>
    
    <!-- 质检弹窗模板 -->
    <script type="text/html" id="qualityCheckTpl">
        <form class="layui-form" lay-filter="qualityForm" style="padding: 20px;">

             <!-- 添加工序ID隐藏域 -->
        <input type="hidden" id="processFlowSheetId" name="processFlowSheetId">

          <div class="layui-form-item">
            <label class="layui-form-label">工序编号</label>
            <div class="layui-input-block">
                 <input name="processCode" id="processCode" class="layui-input" readonly/>
            </div>
          </div>

           <div class="layui-form-item">
            <label class="layui-form-label">工序名称</label>
            <div class="layui-input-block">
              <input name="processName" id="processName" class="layui-input" readonly/>
            </div>
          </div>

           <div class="layui-form-item">
            <label class="layui-form-label">所在部门</label>
            <div class="layui-input-block">
              <input name="pepartment" id="pepartment" class="layui-input" readonly/>
            </div>
          </div>

           <div class="layui-form-item">
            <label class="layui-form-label">负责人</label>
            <div class="layui-input-block">
              <input name="pesponsiblePerson" id="pesponsiblePerson" class="layui-input" readonly/>
            </div>
          </div>


           <div class="layui-form-item">
            <label class="layui-form-label">完工数量</label>
            <div class="layui-input-block">
              <input type="number"  name="plannedQuantity" id="plannedQuantity" class="layui-input" readonly/>
            </div>
          </div>

           <div class="layui-form-item">
            <label class="layui-form-label">合格数量</label>
            <div class="layui-input-block">
              <input name="heGeNumber" id="heGeNumber" class="layui-input" type="number"/>
            </div>
          </div>

          <div class="layui-form-item">
            <label class="layui-form-label">不良数量</label>
            <div class="layui-input-block">
              <input name="buLiANGnumber" id="buLiANGnumber" class="layui-input" type="number"/>
            </div>
          </div>

        </form>
    </script>



    @*  //在html代码中添加一个隐藏的模版，用于展示物品清单表格 *@
    <script type="text/html" id="materialListTemplate">
        <div style="padding: 10px;">
            <table class="layui-table" id="materialListTable">
                <thead>
                    <tr>
                        <th>序号</th>
                        <th>物品编号</th>
                        <th>物品名称</th>
                        <th>型号型号</th>
                        <th>单位</th>
                        <th>物品类别</th>
                        <th>物品分类</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>
    </script>


    <!-- 引用本地 layui.js -->
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="~/lib/layuiadmin/layui/layui.all.js"></script>

    <!--报工记录--开始-->
    <script>
        layui.use(['element', 'form', 'table', 'jquery', 'layer'], function () {
            var element = layui.element;
            var form = layui.form;
            var table = layui.table;
            // var dropdown = layui.dropdown;
            var layer = layui.layer;
            var $ = layui.jquery;

            // 导航切换功能
            element.on('nav(navFilter)', function (elem) {
                var pageId = elem.attr('data-page');
                showPage(pageId);
            });

            // 页面切换函数
            function showPage(pageId) {
                $('.page-content').hide();
                $('#' + pageId).show();
            }

            // 初始化显示默认页面
            showPage('basicInfo');

            // 右上角按钮功能
            $('#btnOnline').click(function () {
                layer.msg('执行上线操作');
            });

            $('#btnClose').click(function () {
                layer.confirm('确认关闭工单吗？', function (index) {
                    layer.msg('执行关闭操作');
                    layer.close(index);
                });
            });

            $('#btnPrint').click(function () {
                layer.msg('执行打印操作');
            });


            table.render({
                elem: '#ID-table-demo-filter',
                url: 'http://localhost:5234/api/WorkOrder/GetSCWorkOrderLC', // 此处为静态模拟数据，实际使用时需换成真实接口
                // url: "@ViewBag.BaseUrl/T7/WorkOrder/GetSCWorkOrderLC",
                toolbar: 'default',
                height: 600,
                page:true,
                limit: 6,
                limits: [6,8,10,15],
                cols: [[
                    { type: 'checkbox', fixed: 'left' },
                    { field: 'processFlowSheetId', title: '序号', width: 80, fixed: 'left' },
                    { field: 'processCode', title: '工序编码', width: 120 },
                    { field: 'processName', title: '工序名称' },
                    { field: 'processingOrder', title: '加工顺序' },
                    { field: 'processFlow', title: '工艺流程' },
                    { field: 'pesponsiblePerson', title: '负责人' },
                    { field: 'pepartment', title: '所在部门' },
                    { field: 'plannedStartDate', title: '开始时间' },
                    { field: 'plannedEndDate', title: '结束时间' },
                    { field: 'plannedQuantity', title: '计划产量' },
                    { field: 'heGeNumber', title: '合格产量' },
                    { field: 'buLiANGnumber', title: '不良产量' },
                    {
                        field: 'zjStatus',
                        title: '状态',
                        templet: function (d) {
                            return d.zjStatus ? '已质检' : '未质检';
                        }
                    },
                    { fixed: 'right', title: '操作', width: 134, minWidth: 125, templet: '#toolDemo' }
                ]],
                done: function () {
                    // 记录筛选状态
                    var that = this;
                    that.elem.next().on('mousedown', 'input[lay-filter="LAY_TABLE_TOOL_COLS"]+', function () {
                        var input = $(this).prev()[0];
                        // 此处表名可任意定义
                        layui.data('table-filter-test', {
                            key: input.name
                            , value: input.checked
                        })
                    });
                }
            });

            // 重点！必须在 layui.use 回调内注册事件监听
            table.on('tool(demoFilter)', function (obj) {
                var data = obj.data; // 当前行数据

                if (obj.event === 'qualityCheck') {
                    // 打开质检弹窗
                    layer.open({
                        type: 1,
                        title: '质量检查 - ' + data.processName,
                        area: ['800px', '650px'],
                        content: $('#qualityCheckTpl').html(),
                        btn: ['提交质检', '取消'],
                        success: function (layero, index) {
                            // 反填数据到表单
                            form.val('qualityForm', { // 使用form模块的val方法批量赋值
                                "processFlowSheetId": data.processFlowSheetId,
                                "processCode": data.processCode,
                                "processName": data.processName,
                                "pesponsiblePerson": data.pesponsiblePerson,
                                "pepartment": data.pepartment,
                                "plannedQuantity": data.plannedQuantity,
                                 "heGeNumber": data.heGeNumber || null,  // 匹配后端字段
                                 "buLiANGnumber": data.buLiANGnumber || null  // 匹配后端字段
                            });
                        },
                        yes: function (index) {
                            // 获取表单数据（关键修正点）
                            var formData = {
                                processFlowSheetId: $('#processFlowSheetId').val(),
                                heGeNumber: $('#heGeNumber').val(),
                                buLiANGnumber: $('#buLiANGnumber').val(),
                            }

                            // 添加必要验证
                            if (parseInt(formData.heGeNumber) + parseInt(formData.buLiANGnumber) > data.plannedQuantity) {
                                layer.msg("合格数+不良数不能超过计划产量");
                                return;
                            }

                            // 提交到后端
                            $.ajax({
                                url: 'http://localhost:5090/api/WrokOrder/SCWorkOrderZJ',
                                // url: "@ViewBag.BaseUrl/T8/WrokOrder/SCWorkOrderZJ",
                                type: 'put',
                                contentType: 'application/json',
                                data: JSON.stringify(formData),
                                success: function (res) {
                                    if (res.code === 206) {
                                        // layer.msg('质检提交成功');
                                        layer.confirm('确认质检嘛老板？', { icon: 3 }, function () {
                                            layer.msg('确认', { icon: 1 });
                                        }, function () {
                                            layer.msg('取消质检');
                                        });
                                        layer.close(index);
                                        table.reload('ID-table-demo-filter'); // 刷新表格
                                    } else {
                                        layer.msg(res.msg || '质检提交失败');
                                    }
                                },
                                error: function (xhr) {
                                    layer.msg('请求失败: ' + xhr.statusText);
                                }
                            });
                        }
                    });
                }
            });
        

        });

    </script>
    <!--报工记录--结束-->


    <!--工单信息--开始-->
    <script>
        layui.use(['form', 'laydate', 'layer', 'upload'], function () {
            var form = layui.form;
            var laydate = layui.laydate;
            var layer = layui.layer;
            var upload = layui.upload; // 引入upload模块
            // 日期选择器初始化
            laydate.render({
                elem: '#workOrderDate'
            });
            laydate.render({
                elem: '#selectPlannedStartTime'
            });
            laydate.render({
                elem: '#selectPlannedEndTime'
            });

            // 生成系统编码函数
            function generateSystemNo() {
                const date = new Date();
                const random = Math.floor(Math.random() * 9000 + 1000); // 4位随机数
                return 'SCDH' +
                    date.getFullYear().toString().substr(2) +
                    (date.getMonth() + 1).toString().padStart(2, '0') +
                    date.getDate().toString().padStart(2, '0') +
                    date.getHours().toString().padStart(2, '0') +
                    date.getMinutes().toString().padStart(2, '0') +
                    date.getSeconds().toString().padStart(2, '0') +
                    random;
            }
            // 监听复选框变化
            form.on('checkbox(systemNumber)', function (data) {
                const input = $('#workOrderName');
                if (data.elem.checked) {
                    input.val(generateSystemNo())
                        .prop('readonly', true)
                        .css('background-color', '#f8f8f8');
                } else {
                    input.val('')
                        .prop('readonly', false)
                        .css('background-color', '');
                }
            });
            $('#workOrderName').val(generateSystemNo()).prop('readonly', true);



            // 初始化一个工艺流程空行
            function initEmptyRow() {
                return {
                    processCode: '',
                    processName: '',
                    processingOrder:0,
                    processFlow: '',
                    pesponsiblePerson: '',
                    pepartment: '',
                    plannedStartDate:'',
                    plannedEndDate: '',
                    plannedQuantity: 0,
                    remarks: '暂无',
                };
            }
            // 添加工艺流程行
            function addMaterialRow(material) 
            {
                material = material || initEmptyRow();
                // 动态获取当前最大序号
                let currentMax = 0;
                $('#processFlowBody tr').each(function () {
                    let num = parseInt($(this).find('td:first').text());
                    if (num > currentMax) currentMax = num;
                });
                const newNumber = currentMax + 1;
                var row = '<tr>' +
                    '<td class="sticky-col" style="left: 0;">' + newNumber + '</td>' +
                    '<td><input type="text" id="processCode" name="processCode[]" class="layui-input"></td>' +
                    '<td><input type="text" id="processName" name="processName[]" class="layui-input"></td>' +
                    '<td><input type="number" id="processingOrder" name="processingOrder[]" class="layui-input"></td>' +
                    '<td><input type="text" id="processFlow" name="processFlow[]" class="layui-input"></td>' +
                    '<td><input type="text" id="pesponsiblePerson"  class="layui-input"></td>' +
                    '<td><input type="text" id="pepartment"  class="layui-input"></td>' +
                    '<td><input type="date" id="plannedStartDate"  class="layui-input "></td>' +
                    '<td><input type="date"  id="plannedEndDate" name="plannedEndDate[]" class="layui-input "></td>' +
                    '<td><input type="number" id="plannedQuantity" name="plannedQuantity[]" class="layui-input"></td>' +
                    '<td><input type="text" id="remarks" name="remarks[]" class="layui-input"></td>' +
                    '<td class="sticky-col" style="right: 0;">' +
                    '<button type="button" class="layui-btn layui-btn-xs move-up">上移</button>' +
                    '<button type="button" class="layui-btn layui-btn-xs move-down">下移</button>' +
                    '<button type="button" class="layui-btn layui-btn-xs layui-btn-danger delete-row">删除</button>' +
                    '</td>' +
                    '</tr>';
                $('#processFlowBody').append(row);
                form.render();
            }
            // 初始化一个空行
            addMaterialRow();

            // 新增生产工单按钮点击事件
            $('#addProcessFlowRow').click(function () {
                addMaterialRow();
            });

            

            // 上移行
            $(document).on('click', '.move-up', function () {
                var $row = $(this).closest('tr');
                if ($row.prev().length > 0) {
                    $row.prev().before($row);
                }
            });

            // 下移行
            $(document).on('click', '.move-down', function () {
                var $row = $(this).closest('tr');
                if ($row.next().length > 0) {
                    $row.next().after($row);
                }
            });

            // 删除行
            $(document).on('click', '.delete-row', function () {
                $(this).closest('tr').remove();
            });





            //物品信息弹出框
            function showMaterialList() {
                layer.open({
                    type: 1,
                    title: '选择物品',
                    area: ['800px', '500px'],
                    content: $('#materialListTemplate').html(), // 假设后面会创建一个物品清单模板
                    success: function (layero) {
                        // 调用接口获取物料数据
                        $.ajax({
                            url: 'http://localhost:5234/api/WorkOrder/GetWuPinname',
                            // url: "@ViewBag.BaseUrl/T7/WorkOrder/GetWuPinname",
                            type: 'GET',
                            success: function (res) {
                                if (res.code === 210) {
                                    var materialList = res.data;
                                    var tableBody = $('#materialListTable tbody');
                                    tableBody.empty();
                                    materialList.forEach(function (material) {
                                        var row = $('<tr>');
                                        row.append($('<td>').text(material.item_classification_detailID));
                                        row.append($('<td>').text(material.item_number));
                                        row.append($('<td>').text(material.item_name));
                                        row.append($('<td>').text(material.specification_model));
                                        row.append($('<td>').text(material.unit));
                                        row.append($('<td>').text(material.item_category));
                                        row.append($('<td>').text(material.item_classification));
                                        row.append($('<td>').html('<button class="layui-btn layui-btn-xs selectMaterialConfirm">确认</button>'));
                                        row.data('material', material);
                                        tableBody.append(row);
                                    });
                                    form.render();
                                } else {
                                    layer.msg(res.msg || '获取物料数据失败', { icon: 2 });
                                }
                            },
                            error: function (xhr, status, error) {
                                layer.msg('请求失败: ' + error, { icon: 2 });
                                console.error(xhr.responseText);
                            }
                        });
                    }
                });
            }
            //选择按钮绑定点击事件
            $(document).on('click', '.selectMaterialButton', function () {
                showMaterialList();
            });
            //处理"确定选择"按钮后的回填操作
            $(document).on('click', '.selectMaterialConfirm', function () {
                var material = $(this).closest('tr').data('material');
                $('#itemNumber').val(material.item_number);
                $('#itemName').val(material.item_classification_detailID);
                $('#specification').val(material.specification_model);
                $('#unit').val(material.unit);
                $('#itemCategory').val(material.item_category);
                $('#itemClassification').val(material.item_classification);
                form.render();
                layer.closeAll('page'); // 关闭物品清单弹窗
            });
            // 获取关联生产单号列表--下拉框
            $.ajax({
                url: 'http://localhost:5234/api/WorkOrder/GetSCDanHao', // 替换为实际的 API 地址
                // url: "@ViewBag.BaseUrl/T7/WorkOrder/GetSCDanHao",
                type: 'GET',
                success: function (res) {
                    if (res.code === 210) {
                        var productionOrderNumbers = res.data;
                        var select = $('#associatedProductionOrderNumber');
                        productionOrderNumbers.forEach(function (number) {
                            select.append('<option value="' + number.associatedProductionOrderId + '">' + number.associatedProductionName + '</option>');
                        });
                        form.render('select');
                    } else {
                        layer.msg(res.msg || '获取生产单号列表失败', { icon: 2 });
                    }
                },
                error: function (xhr, status, error) {
                    layer.msg('请求失败: ' + error, { icon: 2 });
                    console.error(xhr.responseText);
                }
            });



            // 给自定义上传按钮绑定点击事件
            $("#uploadButton").click(function () {
                $("#wenJian").click();
            });

            // 图片上传功能
            $("#wenJian").change(function () {
                var files = this.files;
                var uploadCount = 0;
                for (var i = 0; i < files.length; i++) {
                    var file = files[i];
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        var img = $("<img>").attr({
                            src: e.target.result,
                            width: '100px',
                            height: '100px',
                            margin: '5px',
                            border: '1px solid #eee',
                            padding: '2px'
                        });
                        var progressDiv = $("<div>").addClass("upload-progress");
                        var progressBar = $("<div>").addClass("upload-progress-bar");
                        progressBar.append($("<span>"));
                        progressDiv.append(progressBar);
                        var previewItem = $("<div>").append(img).append(progressDiv);
                        $('#imagePreview').append(previewItem);

                        var formData = new FormData();
                        formData.append('file', file);

                        $.ajax({
                            url: 'http://localhost:5090/api/WrokOrder/UploadPic',
                            // url: "@ViewBag.BaseUrl/T8/WrokOrder/UploadPic",
                            type: 'POST',
                            data: formData,
                            processData: false,
                            contentType: false,
                            xhr: function () {
                                var xhr = new XMLHttpRequest();
                                xhr.upload.addEventListener('progress', function (e) {
                                    if (e.lengthComputable) {
                                        var percentComplete = (e.loaded / e.total) * 100;
                                        progressBar.css('width', percentComplete + '%');
                                    }
                                }, false);
                                return xhr;
                            },
                            success: function (res) {
                                uploadCount++;
                                // 假设后端返回的路径固定为 http://localhost:5090/img/09.jpg
                                var uploadedFilePath = 'http://localhost:5090/img/09.jpg';
                                if (res.status === 200) {
                                    layer.msg('文件' + file.name + '上传成功，存储路径：' + uploadedFilePath, { icon: 1 });
                                } else {
                                    layer.msg('文件' + file.name + '上传失败：' + res.msg, { icon: 2 });
                                }
                                if (uploadCount === files.length) {
                                    layer.msg('所有文件上传完成', { icon: 1 });
                                }
                            },
                            error: function (xhr) {
                                uploadCount++;
                                layer.msg('文件' + file.name + '上传失败：' + xhr.status, { icon: 2 });
                                if (uploadCount === files.length) {
                                    layer.msg('所有文件上传完成', { icon: 1 });
                                }
                            }
                        });
                    };
                    reader.readAsDataURL(file);
                }
            });



////////////////////基本详情反填
            // 从URL获取ID参数
            function getQueryParam(name) {
                const params = new URLSearchParams(window.location.search);
                return params.get(name);
            }

            // 页面加载时根据ID查询数据
            $(function () {
                const id = getQueryParam('WorkOrderId');
                if (id) {
                    loadInvoiceData(id);
                } else {
                    layer.msg('未获取到生产单号ID', { icon: 2 });
                }
            });

            // 加载数据 - 修正URL格式
            function loadInvoiceData(id) {
                const loadIndex = layer.load(2, { shade: 0.3 });
                // 使用模板字符串正确拼接URL
                $.ajax({
                    url: `http://localhost:5234/api/WorkOrder/GetSCWorkOrderXQ?WorkOrderId=${id}`,
                    // url: `@ViewBag.BaseUrl/T7/WorkOrder/GetSCWorkOrderXQ?WorkOrderId=${id}`,
                    type: 'GET',
                    dataType: 'json',
                    success: function (res) {
                        layer.close(loadIndex);
                        if (res.code === 0 && res.data?.length > 0) {
                            fillFormData(res.data[0]);
                        } else {
                            layer.msg(res.msg || '数据加载失败', { icon: 2 });
                        }
                    },
                    error: function (xhr) {
                        layer.close(loadIndex);
                        layer.msg(`请求失败: ${xhr.statusText}`, { icon: 2 });
                        console.error('请求详情:', {
                            url: xhr.responseURL,
                            status: xhr.status,
                            response: xhr.responseText
                        });
                    }
                });
            }
            // 填充表单 - 增强健壮性
            function fillFormData(data) {
                try {
                    // 主表单数据
                    const fields = {
                        workOrderName: data.workOrderName,
                        associatedProductionOrderNumber: data.associatedProductionOrderNumber,
                        associatedProject: data.associatedProject,
                        personinCharge: data.personinCharge,
                        remarks: data.remarks,
                        workOrderDate: data.workOrderDate?.split('T')[0],
                        salesOrder: data.salesOrder,
                        affiliatedDepartment: data.affiliatedDepartment,

                        itemName: data.scwName,
                        specification: data.specification,
                        itemCategory: data.itemCategory,
                        plannedStartTime: data.plannedStartTime?.split('T')[0],
                        plannedOutput: data.plannedOutput,
                        itemNumber: data.itemNumber,
                        unit: data.unit,
                        itemClassification: data.itemClassification,
                        plannedEndTime: data.plannedEndTime?.split('T')[0],

                        processCode: data.processCode,
                        processName: data.processName,
                        processingOrder: data.processingOrder,
                        processFlow: data.processFlow,
                        pesponsiblePerson: data.pesponsiblePerson,
                        pepartment: data.pepartment,
                        plannedStartDate: data.plannedStartDate?.split('T')[0],
                        plannedEndDate: data.plannedEndDate?.split('T')[0],
                        plannedQuantity: data.plannedQuantity,
                        // wenJian: data.wenJian
                    };

                    // 设置表单值
                    Object.entries(fields).forEach(([key, value]) => {
                        const $elem = $(`#${key}`);
                        if (value === null || value === undefined) {
                            // 处理空值情况
                            if ($elem.is('select')) {
                                $elem.val('').trigger('change');
                            } else {
                                $elem.val('');
                            }
                        } else {
                            if ($elem.is('select')) {
                                $elem.val(value || '').trigger('change');
                            } else {
                                $elem.val(value || '');
                            }
                        }
                    });

                    form.render();
                } catch (e) {
                    console.error('填充数据出错:', e);
                    layer.msg('数据加载失败，请检查控制台', { icon: 2 });
                }
            }




            // 以下是新增的代码块，放在这里可以确保相关函数已定义
            $(function () {
                const id = getQueryParam('WorkOrderId');
                if (id) {
                    // 刷新页面数据，调用获取数据的函数重新加载
                    loadInvoiceData(id);
                    loadInvoiceData(id);
                } else {
                    layer.msg('未获取到生产单号ID', { icon: 2 });
                }
            });



        });

        



    </script>
    <!--工单信息--结束-->

    <!--操作记录--开始-->
    <script>
        layui.use(['element', 'form', 'table', 'jquery', 'layer'], function () {
            var element = layui.element;
            var form = layui.form;
            var table = layui.table;
            // var dropdown = layui.dropdown;
            var layer = layui.layer;
            var $ = layui.jquery;

            // 导航切换功能
            element.on('nav(navFilter)', function (elem) {
                var pageId = elem.attr('data-page');
                showPage(pageId);
            });

            // 页面切换函数
            function showPage(pageId) {
                $('.page-content').hide();
                $('#' + pageId).show();
            }

            // 初始化显示默认页面
            showPage('basicInfo');

            // 右上角按钮功能
            $('#btnOnline').click(function () {
                layer.msg('执行上线操作');
            });

            $('#btnClose').click(function () {
                layer.confirm('确认关闭工单吗？', function (index) {
                    layer.msg('执行关闭操作');
                    layer.close(index);
                });
            });

            $('#btnPrint').click(function () {
                layer.msg('执行打印操作');
            });

                table.render({
                        elem: '#ID-table-demo-filters',
                        url: 'http://localhost:5234/api/WorkOrder/GetSCWorkOrderJL', // 此处为静态模拟数据，实际使用时需换成真实接口
                        // url: "@ViewBag.BaseUrl/T7/WorkOrder/GetSCWorkOrderJL",
                        toolbar: 'default',
                        height: 600,
                        request: {
                            pageName: 'PageIndex', // 对应后端分页参数名 PageIndex
                            limitName: 'PageSize'  // 对应后端分页参数名 PageSize
                        },
                        // 修正 where 中错误的 DOM 选择器（假设表单字段名正确）
                        where: {

                            CaoName: $('[name="CaoName"]').val()
                        },
                        limit: 15,
                        limits: [2, 4, 6, 8],
                        cols: [[
                            { type: 'checkbox', fixed: 'left' },
                            { field: 'jlId', title: '序号', width: 80, fixed: 'left' },
                            { field: 'caoName', title: '操作人', width: 120 },
                            {
                                field: 'caoTime',
                                title: '操作时间',
                                width: 200,
                                templet: function (d) {
                                    var date = new Date(d.caoTime);
                                    var year = date.getFullYear();
                                    var month = ("0" + (date.getMonth() + 1)).slice(-2);
                                    var day = ("0" + date.getDate()).slice(-2);
                                    var hours = ("0" + date.getHours()).slice(-2);
                                    var minutes = ("0" + date.getMinutes()).slice(-2);
                                    var seconds = ("0" + date.getSeconds()).slice(-2);
                                    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                                }
                            },
                            { field: 'caoNeiRong', title: '操作内容', width: 220 },
                        ]],
                        done: function () {
                            // 记录筛选状态
                            var that = this;
                            that.elem.next().on('mousedown', 'input[lay-filter="LAY_TABLE_TOOL_COLS"]+', function () {
                                var input = $(this).prev()[0];
                                // 此处表名可任意定义
                                layui.data('table-filter-test', {
                                    key: input.name
                                    , value: input.checked
                                })
                            });
                        }
                    });
           


        });

    </script>
    <!--操作记录--结束-->

</body>

</html>